package com.bruce.asurada.user.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bruce.asurada.common.dto.*;
import com.bruce.asurada.user.entity.User;
import com.bruce.asurada.user.mapper.UserMapper;
import com.bruce.asurada.user.service.UserService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
/**
 * 用户服务实现类
 * 
 * @author Bruce
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public void register(UserRegisterDto registerDto) {
        // 检查用户名是否已存在
        User existingUserByUsername = findByUsername(registerDto.getUsername());
        if (existingUserByUsername != null) {
             throw new RuntimeException("用户名已存在");
        }

        // 检查手机号是否已存在
        User existingUserByMobile = findByMobile(registerDto.getMobile());
        if (existingUserByMobile != null) {
            throw new RuntimeException("手机号已存在");
        }

        // 检查邮箱是否已存在
        User existingUserByEmail = findByEmail(registerDto.getEmail());
        if (existingUserByEmail != null) {
            throw new RuntimeException("邮箱已存在");
        }

        // 创建新用户
        User user = new User();
        user.setUsername(registerDto.getUsername());
        user.setPassword(passwordEncoder.encode(registerDto.getPassword()));
        user.setMobile(registerDto.getMobile());
        user.setEmail(registerDto.getEmail());

        userMapper.insert(user);
        log.info("用户注册成功: {}", registerDto.getUsername());
    }


    /**
     * 登录用户
     * @param loginDto
     * @return
     */
    @Override
    public UserInfoDto login(UserLoginDto loginDto){
         // 根据账号查找用户
        User user = findByAccount(loginDto.getAccount());
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 验证密码
        if (!passwordEncoder.matches(loginDto.getPassword(), user.getPassword())) {
            throw new RuntimeException("密码错误");
        }

        UserInfoDto userInfoDto = UserInfoDto.builder().build() ;
        BeanUtils.copyProperties(user, userInfoDto);
        return userInfoDto;
    }


    

    private User findByUsername(String username) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        return userMapper.selectOne(wrapper);
    }

    private User findByMobile(String mobile) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getMobile, mobile);
        return userMapper.selectOne(wrapper);
    }

    private User findByEmail(String email) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getEmail, email);
        return userMapper.selectOne(wrapper);
    }

    private User findByAccount(String account) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, account)
                .or()
                .eq(User::getMobile, account)
                .or()
                .eq(User::getEmail, account);
        return userMapper.selectOne(wrapper);
    }

    @Override
    public UserInfoDto getUserInfo(UserQueryDTO queryDTO) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        Long userId = queryDTO.getId();
        String username = queryDTO.getUsername();
        String mobile = queryDTO.getMobile();
        String email = queryDTO.getEmail();
        if(null != userId){
            wrapper.eq(User::getId, userId);
        }
        if(StringUtils.isNotBlank(username)){
            wrapper.eq(User::getUsername, username);
        }
        if(StringUtils.isNotBlank(mobile)){
            wrapper.eq(User::getMobile, mobile);
        }
        if(StringUtils.isNotBlank(email)){
            wrapper.eq(User::getEmail, email);
        }
        User user = userMapper.selectOne(wrapper);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        UserInfoDto userInfoDto = UserInfoDto.builder().build() ;
        BeanUtils.copyProperties(user, userInfoDto);
        return userInfoDto;
    }
}